package logger

import (
	"os"
	"strings"
	"time"
)

const NormalDateTimeMsPattern = "2006-01-02 15:04:05.000"

type ConsoleAppender struct {
	name   string
	output StringWriter
}

type ConsoleWriter struct {
	pattern string
}

func (w *ConsoleWriter) WriteString(time time.Time, name, level, text string) (n int, err error) {
	if w.pattern == "" {
		return 0, nil
	}
	output := strings.NewReplacer(
		"%d", time.Format(NormalDateTimeMsPattern),
		"%logger", name,
		"%level", level,
		"%msg", text,
		"%n", "\n",
	).Replace(w.pattern)
	return os.Stdout.WriteString(output)
}

func NewConsoleAppender(name, pattern string) *ConsoleAppender {
	return &ConsoleAppender{name: name, output: &ConsoleWriter{pattern: pattern}}
}

func (appender *ConsoleAppender) Name() string {
	return appender.name
}

func (appender *ConsoleAppender) Output() StringWriter {
	return appender.output
}
